<template>
  <div class="delivery-code">
    <!-- 导航栏 -->
    <van-nav-bar
      title="输入提货码"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      class="custom-nav"
    />

    <!-- 页面内容 -->
    <div class="content">
      <!-- 提示信息 -->
      <div class="info-card">
        <div class="info-header">
          <van-icon name="info-o" size="24" color="#667eea" />
          <span>提货码验证</span>
        </div>
        <div class="info-content">
          <p>请输入您收到的提货码以继续预约进场流程</p>
          <p>提货码通常由6-8位数字或字母组成</p>
        </div>
      </div>

      <!-- 输入表单 -->
      <div class="form-card">
        <van-form @submit="onSubmit">
          <div class="form-section">
            <div class="code-input-wrapper">
              <van-field
                v-model="code"
                name="code"
                label="提货码"
                placeholder="请输入提货码"
                :rules="[
                  { required: true, message: '请输入提货码' },
                  { min: 3, message: '提货码至少3位' },
                  { max: 8, message: '提货码最多8位' }
                ]"
                class="code-field"
                maxlength="8"
                clearable
              />
              <div class="input-tips">
                <van-icon name="edit" size="16" color="#999" />
                <span>请手动输入提货码</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="button-section">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              class="verify-button"
              :loading="verifying"
              :disabled="!code || code.length < 3"
            >
              {{ verifying ? '验证中...' : '验证提货码' }}
            </van-button>
          </div>
        </van-form>
      </div>

      <!-- 帮助信息 -->
      <div class="help-card">
        <div class="help-header">
          <van-icon name="question-o" size="20" color="#ff8800" />
          <span>遇到问题？</span>
        </div>
        <div class="help-content">
          <p>• 提货码由发货方提供</p>
          <p>• 如未收到提货码，请联系发货方</p>
          <p>• 提货码输入错误将无法进入预约流程</p>
        </div>
      </div>
    </div>

    <!-- 预约数据弹框 -->
    <van-dialog
      v-model:show="showResult"
      title="预约信息确认"
      :show-cancel-button="false"
      :show-confirm-button="false"
      :close-on-click-overlay="false"
      class="appointment-dialog"
    >
      <div class="dialog-content" v-if="appointmentData">
        <div class="success-tip">
          <van-icon name="success" size="32" color="#07c160" />
          <span>验证成功</span>
        </div>

        <div class="data-section">
          <h3>预约信息</h3>
          <div class="data-row">
            <span class="label">计划名称：</span>
            <span class="value">{{ appointmentData.planName }}</span>
          </div>
          <div class="data-row">
            <span class="label">预约码：</span>
            <span class="value highlight">{{ appointmentData.pickCode }}</span>
          </div>
          <div class="data-row">
            <span class="label">预约时间：</span>
            <span class="value">{{ appointmentData.dispatchtime }}</span>
          </div>
        </div>

        <div class="data-section">
          <h3>司机信息</h3>
          <div class="data-row">
            <span class="label">姓名：</span>
            <span class="value">{{ appointmentData.driverName }}</span>
          </div>
          <div class="data-row">
            <span class="label">车牌号：</span>
            <span class="value">{{ appointmentData.licensePlate }}</span>
          </div>
          <div class="data-row">
            <span class="label">身份证：</span>
            <span class="value">{{ appointmentData.driverIdCard }}</span>
          </div>
        </div>

        <div class="data-section">
          <h3>货物信息</h3>
          <div class="data-row">
            <span class="label">货物名称：</span>
            <span class="value">{{ appointmentData.itemName }}</span>
          </div>
          <div class="data-row">
            <span class="label">规格：</span>
            <span class="value">{{ appointmentData.itemModel || '-' }}</span>
          </div>
          <div class="data-row">
            <span class="label">发货方：</span>
            <span class="value">{{ appointmentData.sendoutCompany }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-buttons">
          <van-button
            plain
            type="default"
            class="dialog-cancel-btn"
            @click="cancelAppointment"
            :disabled="confirming"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            class="dialog-confirm-btn"
            @click="confirmAppointment"
            :loading="confirming"
          >
            {{ confirming ? '保存中...' : '保存' }}
          </van-button>
        </div>
      </template>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog, showSuccessToast } from 'vant'
import businessApi from '../api/business.js'
import { getWechatUnionId, getWechatOpenId } from "../store.js";

const router = useRouter()

// 表单数据
const code = ref('')
const verifying = ref(false)
const confirming = ref(false)

// 预约数据
const appointmentData = ref(null)
const showResult = ref(false)

// 返回首页
const goBack = () => {
  router.push('/')
}

// 提交验证
const onSubmit = async (values) => {
  verifying.value = true
  
  try {
    const fwid = getWechatOpenId();
    
    if (!fwid) {
      showToast('未获取到微信ID，请先从首页授权')
      verifying.value = false
      return
    }
    
    try {
      const response = await businessApi.appointmentBook(code.value, fwid)
      
      console.log('预约验证响应:', response)
      
      // 处理API响应
      if (response && response.code === 200 && response.data) {
        showSuccessToast('提货码验证成功')
        
        // 保存预约数据
        appointmentData.value = response.data
        showResult.value = true
        
        console.log('预约数据:', appointmentData.value)
      } else {
        showToast(response?.msg || '提货码无效，请检查后重新输入')
      }
    } catch (error) {
      if (error.response) {
        console.error('响应数据:', error.response.data)
      }
      throw error
    }
    
  } catch (error) {
    console.error('验证提货码失败:', error)
    console.error('错误详情:', {message: error.message, stack: error.stack})
    showToast('网络异常，请检查网络连接后重试')
  } finally {
    verifying.value = false
  }
}

// 确认预约
const confirmAppointment = async () => {
  if (!appointmentData.value) {
    showToast('预约数据不存在')
    return
  }
  
  confirming.value = true
  
  try {
    const response = await businessApi.appointmentBookConfirm(appointmentData.value)
    
    console.log('确认预约响应:', response)
    
    if (response && response.code === 200) {
      showSuccessToast(response.msg || '预约确认成功')
      
      // 跳转到首页或预约记录页
      setTimeout(() => {
        router.push('/')
      }, 1000)
    } else {
      showToast(response?.msg || '确认失败，请重试')
    }
  } catch (error) {
    console.error('确认预约失败:', error)
    showToast('网络异常，请重试')
  } finally {
    confirming.value = false
  }
}

// 取消预约
const cancelAppointment = () => {
  // 直接关闭弹框
  showResult.value = false
  appointmentData.value = null
  code.value = ''
}
</script>

<style scoped>
.delivery-code {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8faff 0%, #f0f4ff 100%);
  padding-bottom: 20px;
  overflow-y: auto;
}

/* 自定义导航栏 */
.custom-nav {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.custom-nav :deep(.van-nav-bar__title) {
  color: white;
  font-weight: 600;
}

.custom-nav :deep(.van-nav-bar__text) {
  color: white;
}

.custom-nav :deep(.van-icon) {
  color: white;
}

/* 页面内容 */
.content {
  padding: 16px;
}

/* 提示信息卡片 */
.info-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.info-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 16px;
}

.info-header span {
  font-weight: 600;
  color: #2c3e50;
  font-size: 18px;
}

.info-content p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

/* 表单卡片 */
.form-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(102, 126, 234, 0.1);
  margin-bottom: 16px;
}

/* 表单区域 */
.form-section {
  padding: 24px 20px;
}

.code-input-wrapper {
  position: relative;
}

.code-field {
  margin-bottom: 12px;
}

.code-field :deep(.van-field__label) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
  width: auto;
  min-width: 70px;
}

.code-field :deep(.van-field__control) {
  color: #333;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 2px;
}

.code-field :deep(.van-field__control::placeholder) {
  color: #999;
  letter-spacing: normal;
}

.input-tips {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #999;
  font-size: 13px;
  margin-top: 8px;
}

/* 按钮区域 */
.button-section {
  padding: 0 20px 24px 20px;
}

.verify-button {
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 1px;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.verify-button:active {
  transform: translateY(2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.verify-button:disabled {
  background: #ccc;
  box-shadow: none;
}

/* 按钮区域 */
.button-section {
  padding: 0 20px 24px 20px;
}
.help-card {
  background: white;
  border-radius: 12px;
  padding: 18px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 136, 0, 0.1);
}

.help-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.help-header span {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.help-content p {
  margin: 6px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.code-tag {
  display: inline-block;
  background: #667eea;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin: 0 4px 4px 0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.code-tag:hover {
  background: #5a6fd8;
  transform: translateY(-1px);
}

.contact-info {
  margin-top: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #ff8800;
}

.contact-info span {
  color: #2c3e50;
  font-weight: 500;
  font-size: 14px;
}

/* 响应式优化 */
@media screen and (max-width: 375px) {
  .content {
    padding: 12px;
  }
  
  .form-section {
    padding: 20px 16px;
  }
  
  .button-section {
    padding: 0 16px 20px 16px;
  }
}

/* 加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-card,
.form-card,
.help-card {
  animation: fadeInUp 0.6s ease forwards;
}

.form-card {
  animation-delay: 0.1s;
}

.help-card {
  animation-delay: 0.2s;
}

/* 弹框样式 */
.appointment-dialog :deep(.van-dialog) {
  width: 90%;
  max-width: 500px;
  border-radius: 16px;
  overflow: hidden;
}

.appointment-dialog :deep(.van-dialog__header) {
  padding: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
}

.appointment-dialog :deep(.van-dialog__content) {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0;
}

.appointment-dialog :deep(.van-dialog__footer) {
  padding: 0;
  border-top: 1px solid rgba(102, 126, 234, 0.1);
}

/* 弹框内容 */
.dialog-content {
  padding: 20px;
}

.success-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding: 16px;
  background: linear-gradient(135deg, rgba(7, 193, 96, 0.05), rgba(7, 193, 96, 0.02));
  border-radius: 12px;
  border: 1px solid rgba(7, 193, 96, 0.1);
}

.success-tip span {
  font-size: 16px;
  font-weight: 600;
  color: #07c160;
}

/* 数据分组 */
.data-section {
  margin-bottom: 20px;
}

.data-section:last-child {
  margin-bottom: 0;
}

.data-section h3 {
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
}

.data-row {
  display: flex;
  align-items: flex-start;
  padding: 6px 0;
  line-height: 1.6;
}

.data-row .label {
  font-size: 13px;
  color: #8f9bb3;
  min-width: 75px;
  flex-shrink: 0;
}

.data-row .value {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 500;
  flex: 1;
  word-break: break-all;
}

.data-row .value.highlight {
  color: #667eea;
  font-weight: 600;
  font-size: 14px;
  background: rgba(102, 126, 234, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}

/* 弹框按钮 */
.dialog-buttons {
  display: flex;
  gap: 0;
  padding: 0;
}

.dialog-buttons .van-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 0;
  border: none;
}

.dialog-cancel-btn {
  color: #6b7280;
  background: #f3f4f6;
  border-right: 1px solid rgba(102, 126, 234, 0.1) !important;
}

.dialog-cancel-btn:active:not(:disabled) {
  background: #e5e7eb;
}

.dialog-confirm-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.dialog-confirm-btn:active {
  opacity: 0.8;
}
</style>